# 分店
class Admin::StudiosController < Admin::ApplicationController
  layout "admin"
  def index

    p "工作室index"
    if params[:company_id]
      company = Company.find(params[:company_id])
      enter_company(company)
      @studios = Studio.where(company_id: params[:company_id])
    elsif current_company
      @studios = current_company.studios
    end

    @studioDataArray = Array.new();

    today = Date.current;
    p today,today.strftime('%Y-%m-%d');;

    for studio in @studios

      studioHash = Hash.new();
      studioHash["id"] = studio.id;
      studioHash["name"] = studio.name;
      studioHash["invalidate_at"] = studio.invalidate_at;
      # 今日新增学员
      studioHash["day_students"] = studio.students.where("created_at like '%#{today}%'").count;
      
      # 今日营业金额
      good_ids = Good.where(good_type: "课程商品").ids;
      orders = Order.where("created_at like ?", "%#{today}%").where(studio_id: studio.id);
      studioHash["total_price"] = orders.sum("total_price");;
      
      # 今日课程消费
      total_price_lesson = CourseReckon.select("sum(course_reckons.amount) as amount")
                            .where("course_reckons.studio_id = #{studio.id} and course_reckons.created_at like '%#{today}%'");
      courseReckonAmount = total_price_lesson[0].amount;
      if !courseReckonAmount
        courseReckonAmount = 0;
      end
      studioHash["total_price_lesson"] = courseReckonAmount;

      p @studioDataArray.push(studioHash);
    end

    p "=====",@studioDataArray;
    
    #设置当前用户的访问范围,公司or分店
    current_user.scope_to_company
  end

  # kevin
  def update_studio_name
    p "更新工作室名字,update_studio_name"
    studio = Studio.find_by_id(params[:studioId]);
    studio.name = params[:shopName];
    
    respond_to do |format|
      if studio.save

        format.json { render json: {:flag=> 1,:msg => "修改成功!" } }
        format.html { redirect_to admin_studios_url, notice: '修改成功!' }
      else
        format.json { render json: {:flag=> 0,:msg => "修改失败,信息为:#{studio.errors.full_messages.join(',')}!" } }
        format.html { redirect_to admin_studios_url, notice: "修改失败,信息为:#{studio.errors.full_messages.join(',')}!" }
      end
    end
  end

  def new
    @studio = Studio.new()
  end

  def create
    if Company.find_by(owner_id: current_user.id).blank?
      company = Company.new()
      company.name = params[:company_name]
      company.owner_id = current_user.id
      company.save!
      session[:company_id] = company.id
    end

    studio = Studio.new(studio_params)
    studio.company_id = current_company.id
    studio.last_buy_at = DateTime.now
    studio.invalidate_at = DateTime.now.since((params[:duration].to_i).years)
    studio.save!
    
    # 选择分店的时候保存studio_id,kevin
    # session[:studio_id] = studio.id

    current_employee_of_studio = EmployeeOfStudio.find_by(studio_company_id: current_company.id)
    if current_employee_of_studio.present?
      employee = current_employee_of_studio.employee
    else
      employee = Employee.new
      employee.user_id = current_user.id
      employee.company_id = current_company.id
      employee.joined_at = DateTime.now
      employee.status = '在职'
      employee.save!
    end

    employee_of_studio = EmployeeOfStudio.new()
    employee_of_studio.employee_id = employee.id
    employee_of_studio.studio_id = studio.id
    employee_of_studio.employee_user_id = employee.user_id
    employee_of_studio.studio_company_id = studio.company_id
    employee_of_studio.department_id = DepartmentConfiguration.find_by(company_id: studio.company_id, department_name: '主理人').id
    employee_of_studio.position_id = PositionConfiguration.find_by(company_id: studio.company_id, position_name: '主理人').id
    employee_of_studio.position_name = '主理人'
    employee_of_studio.save!

    create_more_studios current_company, employee if params[:studios_name].present?
    redirect_to finish_paying_admin_companies_path
  end

  def finish_paying
  end


  def switch_studio  
    session.delete(:studio_id)
    @current_studio = nil
    redirect_to admin_studios_path
  end

  private
  def studio_params
    params.require(:studio).permit(:name, :uuid, :avatar, :is_chain, :disabled, :deleted_at, :last_buy_at, :invalidate_at, :company_id)
  end

  def create_more_studios current_company, employee
    params[:studios_name].zip(params[:studios_duration]).each do |name,duration|
      studio = Studio.create! name: name, company_id: current_company.id, last_buy_at: DateTime.now, invalidate_at: DateTime.now.since((duration.to_i).years)
      department = DepartmentConfiguration.find_by(company_id: studio.company_id, department_name: '主理人')
      position = PositionConfiguration.find_by(company_id: studio.company_id, position_name: '主理人')
      EmployeeOfStudio.create! employee_id: employee.id, studio_id: studio.id, employee_user_id: employee.user_id,
        studio_company_id: studio.company_id, department_id: department.id , position_id: position.id
    end
  end

end
